// 测评内容管理模块
const EvaluationContentModule = {
    currentTab: 'indicators',

    // 初始化
    init() {
        this.switchTab('indicators');
    },

    // Tab切换
    switchTab(tabName) {
        this.currentTab = tabName;
        
        // 切换Tab活动状态
        document.querySelectorAll('#evaluation-content-management .tab').forEach(tab => {
            tab.classList.remove('active');
        });
        document.querySelectorAll('#evaluation-content-management .tab-content').forEach(content => {
            content.classList.remove('active');
        });

        // 激活选中的Tab
        const targetTab = document.querySelector(`#evaluation-content-management .tab[onclick*="${tabName}"]`);
        if (targetTab) {
            targetTab.classList.add('active');
        }
        const targetContent = document.getElementById(tabName + '-tab');
        if (targetContent) {
            targetContent.classList.add('active');
        }

        // 加载对应数据
        switch(tabName) {
            case 'indicators':
                this.loadIndicatorsList();
                break;
            case 'points':
                this.loadIndicatorOptions(); // 先加载指标选项
                this.loadIndicatorPointsList();
                break;
            case 'weights':
                this.loadIndicatorWeightsList();
                break;
        }
    },

    // ========== 考核指标管理 ==========
    loadIndicatorsList(page = 1) {
        console.log('loadIndicatorsList called with page:', page);
        
        // 先尝试简单的无分页查询，确保基本功能工作
        let url = `${CommonModule.globalConfig.apiBase}/indicators`;
        
        // 获取搜索条件
        const indicatorName = document.getElementById('indicatorNameSearch')?.value;
        const indicatorType = document.getElementById('indicatorTypeSearch')?.value;
        
        console.log('Search conditions:', { indicatorName, indicatorType });
        
        // 如果有搜索条件，使用分页接口
        if ((indicatorName && indicatorName.trim()) || indicatorType) {
            const params = new URLSearchParams();
            params.append('page', page);
            params.append('size', 10);
            
            if (indicatorName && indicatorName.trim()) {
                params.append('zbmc', indicatorName.trim());
            }
            if (indicatorType) {
                params.append('khfs', indicatorType);
            }
            
            url = `${CommonModule.globalConfig.apiBase}/indicators/list?${params}`;
        }
        
        console.log('API URL:', url);

        fetch(url)
            .then(response => {
                console.log('API Response status:', response.status);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('API Data:', data);
                if (data.code === 200) {
                    // 处理不同的数据结构
                    const indicators = data.data.records || data.data;
                    this.renderIndicatorsTable(indicators);
                    
                    // 如果有分页信息，创建分页组件
                    if (data.data.total && data.data.total > 0) {
                        const totalPages = Math.ceil(data.data.total / 10);
                        CommonModule.createPagination('indicatorsPagination', totalPages, page, (p) => this.loadIndicatorsList(p));
                    } else {
                        // 清空分页容器
                        const paginationContainer = document.getElementById('indicatorsPagination');
                        if (paginationContainer) {
                            paginationContainer.innerHTML = '';
                        }
                    }
                } else {
                    console.error('API Error:', data.message);
                    alert('加载失败: ' + (data.message || '未知错误'));
                }
            })
            .catch(error => {
                console.error('Request Error:', error);
                alert('网络错误，请稍后重试: ' + error.message);
            });
    },

    renderIndicatorsTable(indicators) {
        console.log('renderIndicatorsTable called with:', indicators);
        
        // 确保我们在正确的标签页
        const indicatorsTab = document.getElementById('indicators-tab');
        const isTabActive = indicatorsTab && indicatorsTab.classList.contains('active');
        console.log('Indicators tab active:', isTabActive);
        
        if (!isTabActive) {
            console.warn('Indicators tab is not active, switching to it...');
            this.switchTab('indicators');
        }
        
        // 多种方式查找表格元素
        let tbody = document.getElementById('indicatorsTableBody');
        if (!tbody) {
            tbody = document.querySelector('#indicatorsTableContent table tbody');
        }
        if (!tbody) {
            tbody = document.querySelector('#indicators-tab table tbody');
        }
        
        console.log('Found tbody element:', tbody);
        console.log('Tbody parent:', tbody?.parentElement);
        console.log('Tbody visible:', tbody ? window.getComputedStyle(tbody).display : 'N/A');
        
        if (!tbody) {
            console.error('无法找到指标表格的tbody元素');
            
            // 检查所有可能的表格位置
            const tableContent = document.getElementById('indicatorsTableContent');
            const indicatorsTabContent = document.getElementById('indicators-tab');
            
            console.log('Table content element:', tableContent);
            console.log('Indicators tab element:', indicatorsTabContent);
            
            if (tableContent) {
                console.log('Table content HTML:', tableContent.innerHTML);
            }
            
            // 尝试创建表格结构
            if (tableContent && !tableContent.querySelector('table')) {
                console.log('Creating table structure...');
                tableContent.innerHTML = `
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>指标编号</th>
                                <th>指标名称</th>
                                <th>排序</th>
                                <th>考核方式</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="indicatorsTableBody">
                        </tbody>
                    </table>
                `;
                tbody = document.getElementById('indicatorsTableBody');
            }
            
            if (!tbody) {
                console.error('Still cannot find tbody, aborting...');
                return;
            }
        }

        console.log('Clearing table...');
        tbody.innerHTML = '';
        
        if(indicators && indicators.length > 0) {
            console.log('Rendering', indicators.length, 'indicators');
            
            // 使用文档片段提高性能
            const fragment = document.createDocumentFragment();
            
            indicators.forEach((indicator, index) => {
                console.log(`Rendering indicator ${index}:`, indicator);
                const row = document.createElement('tr');
                
                // 安全地处理数据
                const zbbh = indicator.zbbh || '';
                const zbmc = indicator.zbmc || '';
                const px = indicator.px || '';
                const khfs = indicator.khfs || '';
                const khfsText = khfs === '0' ? '对教师' : khfs === '1' ? '对部门' : '';
                
                row.innerHTML = `
                    <td>${zbbh}</td>
                    <td>${zbmc}</td>
                    <td>${px}</td>
                    <td>${khfsText}</td>
                    <td>
                        <button class="btn btn-primary btn-sm" onclick="EvaluationContentModule.showIndicatorModal(${JSON.stringify(indicator).replace(/"/g, '&quot;')})">编辑</button>
                        <button class="btn btn-danger btn-sm" onclick="EvaluationContentModule.deleteIndicator('${zbbh}')">删除</button>
                    </td>
                `;
                fragment.appendChild(row);
            });
            
            tbody.appendChild(fragment);
            console.log('Table rendering completed, rows count:', tbody.children.length);
            
            // 强制重绘
            tbody.style.display = 'none';
            tbody.offsetHeight; // 触发重排
            tbody.style.display = '';
            
        } else {
            console.log('No indicators data, showing empty message');
            tbody.innerHTML = '<tr><td colspan="5">暂无数据</td></tr>';
        }
        
        // 确保表格可见
        const table = tbody.closest('table');
        if (table) {
            table.style.display = 'table';
        }
    },

    showIndicatorModal(data = null) {
        const isEdit = data !== null;
        const title = isEdit ? '编辑考核指标' : '新增考核指标';
        
        const content = `
            <form id="indicatorForm">
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">指标编号</label>
                        <input type="text" name="zbbh" class="form-input" value="${isEdit ? data.zbbh : ''}" 
                               ${isEdit ? 'readonly' : ''} placeholder="${isEdit ? '' : '请输入指标编号'}" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">指标名称</label>
                        <input type="text" name="zbmc" class="form-input" value="${isEdit ? data.zbmc : ''}" required>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">考核方式</label>
                        <select name="khfs" class="form-input">
                            <option value="">请选择</option>
                            <option value="0" ${isEdit && data.khfs === '0' ? 'selected' : ''}>对教师</option>
                            <option value="1" ${isEdit && data.khfs === '1' ? 'selected' : ''}>对部门</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">排序</label>
                        <input type="number" name="px" class="form-input" value="${isEdit ? data.px : 1}" min="1">
                    </div>
                </div>
                <div style="text-align: right; margin-top: 20px;">
                    <button type="button" class="btn btn-secondary" onclick="CommonModule.closeModal()">取消</button>
                    <button type="button" class="btn btn-primary" onclick="EvaluationContentModule.saveIndicator(${isEdit})">${isEdit ? '更新' : '保存'}</button>
                </div>
            </form>
        `;
        
        CommonModule.showModal(title, content);
        window.currentEditData = data;
    },

    saveIndicator(isEdit) {
        const form = document.getElementById('indicatorForm');
        const formData = new FormData(form);
        
        // 验证必填字段
        const zbbh = formData.get('zbbh');
        const zbmc = formData.get('zbmc');
        
        if (!zbbh || !zbbh.trim()) {
            alert('请输入指标编号');
            return;
        }
        
        if (!zbmc || !zbmc.trim()) {
            alert('请输入指标名称');
            return;
        }
        
        const indicatorData = {
            zbbh: zbbh.trim(),
            zbmc: zbmc.trim(),
            khfs: formData.get('khfs'),
            px: formData.get('px') || '1'
        };

        const url = isEdit ?
            `/indicators/${window.currentEditData.zbbh}` :
            '/indicators';
        const method = isEdit ? 'PUT' : 'POST';

        CommonModule.apiRequest(url, {
            method: method,
            body: JSON.stringify(indicatorData)
        })
        .then(response => response.json())
        .then(result => {
            if (result.code === 200) {
                CommonModule.showSuccess(isEdit ? '更新成功' : '添加成功');
                CommonModule.closeModal();
                this.loadIndicatorsList();
            } else {
                alert(`${isEdit ? '更新' : '添加'}失败：${result.message}`);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '保存指标');
        });
    },

    editIndicator(zbbh) {
        CommonModule.apiRequest(`/indicators/${zbbh}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    this.showIndicatorModal(data.data);
                } else {
                    alert('获取指标信息失败：' + data.message);
                }
            })
            .catch(error => {
                CommonModule.handleApiError(error, '获取指标详情');
            });
    },

    deleteIndicator(zbbh) {
        if (!CommonModule.confirmAction('确认删除该考核指标？删除后不可恢复。')) {
            return;
        }

        CommonModule.apiRequest(`/indicators/${zbbh}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                CommonModule.showSuccess('删除成功');
                this.loadIndicatorsList();
            } else {
                alert('删除失败：' + data.message);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '删除指标');
        });
    },

    searchIndicators() {
        console.log('searchIndicators called');
        this.loadIndicatorsList(1);
    },

    importIndicators() {
        console.log('导入考核指标');
    },

    exportIndicators() {
        window.location.href = CommonModule.globalConfig.apiBase + '/export/indicators';
    },

    // ========== 考核点管理 ==========
    loadIndicatorOptions() {
        CommonModule.apiRequest('/indicators')
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    const select = document.getElementById('pointIndicatorSearch');
                    if (select) {
                        select.innerHTML = '<option value="">选择指标</option>';
                        data.data.forEach(indicator => {
                            const option = document.createElement('option');
                            option.value = indicator.zbbh;
                            option.textContent = `${indicator.zbmc} (${indicator.zbbh})`;
                            select.appendChild(option);
                        });
                    }
                }
            })
            .catch(error => {
                console.error('加载指标选项失败:', error);
            });
    },

    loadIndicatorPointsList(page = 1) {
        const params = new URLSearchParams();
        params.append('page', page);
        params.append('size', 15);

        // 获取搜索条件
        const indicatorId = document.getElementById('pointIndicatorSearch')?.value;
        const pointName = document.getElementById('pointNameSearch')?.value;
        
        if (indicatorId) {
            params.append('zbbh', indicatorId);
        }
        if (pointName && pointName.trim()) {
            params.append('khdmc', pointName.trim());
        }

        CommonModule.apiRequest(`/indicators/points/list?${params}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    this.renderIndicatorPointsTable(data.data.records || data.data);
                    // 如果有分页信息，创建分页组件
                    if (data.data.total && data.data.total > 0) {
                        const totalPages = Math.ceil(data.data.total / 15);
                        CommonModule.createPagination('indicatorPointsPagination', totalPages, page, (p) => this.loadIndicatorPointsList(p));
                    }
                } else {
                    CommonModule.handleApiError(new Error(data.message || '加载失败'), '加载考核点');
                }
            })
            .catch(error => {
                CommonModule.handleApiError(error, '加载考核点');
            });
    },

    renderIndicatorPointsTable(points) {
        const tbody = document.querySelector('#indicatorPointsTableContent table tbody');
        if (!tbody) return;

        tbody.innerHTML = '';
        if(points && points.length > 0) {
            points.forEach(point => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${point.zbbh || ''}</td>
                    <td>${point.zbmc || ''}</td>
                    <td>${point.khdbh || ''}</td>
                    <td>${point.khdmc || ''}</td>
                    <td>
                        <button class="btn btn-primary btn-small" onclick="EvaluationContentModule.editIndicatorPoint('${point.zbbh}', '${point.khdbh}')">编辑</button>
                        <button class="btn btn-danger btn-small" onclick="EvaluationContentModule.deleteIndicatorPoint('${point.zbbh}', '${point.khdbh}')">删除</button>
                    </td>
                `;
                tbody.appendChild(row);
            });
        } else {
            tbody.innerHTML = '<tr><td colspan="5">暂无数据</td></tr>';
        }
    },

    showIndicatorPointModal(data = null) {
        const isEdit = data !== null;
        const title = isEdit ? '编辑考核点' : '新增考核点';
        
        const content = `
            <form id="indicatorPointForm">
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">指标编号</label>
                        <input type="text" name="zbbh" class="form-input" value="${isEdit ? data.zbbh : ''}" ${isEdit ? 'readonly' : ''} required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">考核点编号</label>
                        <input type="text" name="khdbh" class="form-input" value="${isEdit ? data.khdbh : ''}" ${isEdit ? 'readonly' : ''} required>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">考核点名称</label>
                        <input type="text" name="khdmc" class="form-input" value="${isEdit ? data.khdmc : ''}" required>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">考核点详解</label>
                        <textarea name="khdxj" class="form-input" rows="3">${isEdit ? (data.khdxj || '') : ''}</textarea>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">A选项分数</label>
                        <input type="number" name="a" class="form-input" value="${isEdit ? data.a : 0}" step="0.1">
                    </div>
                    <div class="form-group">
                        <label class="form-label">B选项分数</label>
                        <input type="number" name="b" class="form-input" value="${isEdit ? data.b : 0}" step="0.1">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">C选项分数</label>
                        <input type="number" name="c" class="form-input" value="${isEdit ? data.c : 0}" step="0.1">
                    </div>
                    <div class="form-group">
                        <label class="form-label">D选项分数</label>
                        <input type="number" name="d" class="form-input" value="${isEdit ? data.d : 0}" step="0.1">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">E选项分数</label>
                        <input type="number" name="e" class="form-input" value="${isEdit ? data.e : 0}" step="0.1">
                    </div>
                </div>
                <div style="text-align: right; margin-top: 20px;">
                    <button type="button" class="btn btn-secondary" onclick="CommonModule.closeModal()">取消</button>
                    <button type="button" class="btn btn-primary" onclick="EvaluationContentModule.saveIndicatorPoint(${isEdit})">${isEdit ? '更新' : '保存'}</button>
                </div>
            </form>
        `;
        
        CommonModule.showModal(title, content);
        window.currentEditData = data;
    },

    saveIndicatorPoint(isEdit) {
        const form = document.getElementById('indicatorPointForm');
        const formData = new FormData(form);
        
        const pointData = {
            zbbh: formData.get('zbbh'),
            khdbh: formData.get('khdbh'),
            khdmc: formData.get('khdmc'),
            khdxj: formData.get('khdxj'),
            a: parseFloat(formData.get('a')) || 0,
            b: parseFloat(formData.get('b')) || 0,
            c: parseFloat(formData.get('c')) || 0,
            d: parseFloat(formData.get('d')) || 0,
            e: parseFloat(formData.get('e')) || 0
        };
        
        const url = isEdit ? 
            `/indicators/points/${window.currentEditData.zbbh}/${window.currentEditData.khdbh}` : 
            '/indicators/points';
        const method = isEdit ? 'PUT' : 'POST';
        
        CommonModule.apiRequest(url, {
            method: method,
            body: JSON.stringify(pointData)
        })
        .then(response => response.json())
        .then(result => {
            if (result.code === 200) {
                CommonModule.showSuccess(isEdit ? '更新成功' : '添加成功');
                CommonModule.closeModal();
                this.loadIndicatorPointsList();
            } else {
                alert(`${isEdit ? '更新' : '添加'}失败：${result.message}`);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '保存考核点');
        });
    },

    editIndicatorPoint(zbbh, khdbh) {
        CommonModule.apiRequest(`/indicators/points/${zbbh}/${khdbh}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    this.showIndicatorPointModal(data.data);
                } else {
                    alert('获取考核点信息失败：' + data.message);
                }
            })
            .catch(error => {
                CommonModule.handleApiError(error, '获取考核点详情');
            });
    },

    deleteIndicatorPoint(zbbh, khdbh) {
        if (!CommonModule.confirmAction('确认删除该考核点？删除后不可恢复。')) {
            return;
        }

        CommonModule.apiRequest(`/indicators/points/${zbbh}/${khdbh}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                CommonModule.showSuccess('删除成功');
                this.loadIndicatorPointsList();
            } else {
                alert('删除失败：' + data.message);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '删除考核点');
        });
    },

    searchIndicatorPoints() {
        this.loadIndicatorPointsList(1);
    },

    importIndicatorPoints() {
        console.log('导入考核点');
    },

    exportIndicatorPoints() {
        window.location.href = CommonModule.globalConfig.apiBase + '/export/indicator-points';
    },

    // ========== 指标权重管理 ==========
    loadIndicatorWeightsList(page = 1) {
        // 获取搜索条件
        const evaluationType = document.getElementById('weightTypeSearch')?.value;
        
        // 如果有搜索条件，使用分页接口
        if (evaluationType && evaluationType.trim()) {
            const params = new URLSearchParams();
            params.append('page', page);
            params.append('size', 10000); // 每页10000条，查出所有数据
            params.append('evaluationType', evaluationType.trim());
            
            CommonModule.apiRequest(`/indicator-weights/list?${params}`)
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        const weights = data.data.list || data.data.records || [];
                        this.renderIndicatorWeightsTable(weights);
                    } else {
                        CommonModule.handleApiError(new Error(data.message || '加载失败'), '加载指标权重');
                    }
                })
                .catch(error => {
                    CommonModule.handleApiError(error, '加载指标权重');
                });
        } else {
            // 没有搜索条件，使用全部数据接口
            CommonModule.apiRequest('/indicator-weights')
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        this.renderIndicatorWeightsTable(data.data);
                    } else {
                        CommonModule.handleApiError(new Error(data.message || '加载失败'), '加载指标权重');
                    }
                })
                .catch(error => {
                    CommonModule.handleApiError(error, '加载指标权重');
                });
        }
    },

    renderIndicatorWeightsTable(weights) {
        const tbody = document.querySelector('#indicatorWeightsTableContent table tbody');
        if (!tbody) return;

        tbody.innerHTML = '';
        if(weights && weights.length > 0) {
            weights.forEach(weight => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${weight.qzbh || ''}</td>
                    <td>${weight.qzmc || ''}</td>
                    <td>${weight.qz || ''}</td>
                    <td>${weight.cplx === '1' ? '对部门' : '对教师'}</td>
                    <td>
                        <button class="btn btn-primary btn-small" onclick="EvaluationContentModule.editIndicatorWeight('${weight.qzbh}')">编辑</button>
                        <button class="btn btn-danger btn-small" onclick="EvaluationContentModule.deleteIndicatorWeight('${weight.qzbh}')">删除</button>
                    </td>
                `;
                tbody.appendChild(row);
            });
        } else {
            tbody.innerHTML = '<tr><td colspan="5">暂无数据</td></tr>';
        }
    },

    showIndicatorWeightModal(data = null) {
        const isEdit = data !== null;
        const title = isEdit ? '编辑指标权重' : '新增指标权重';
        
        const content = `
            <form id="indicatorWeightForm">
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">权重编号</label>
                        <input type="text" name="qzbh" class="form-input" value="${isEdit ? data.qzbh : ''}" 
                               ${isEdit ? 'readonly' : ''} placeholder="${isEdit ? '' : '系统自动生成'}">
                    </div>
                    <div class="form-group">
                        <label class="form-label">权重名称</label>
                        <input type="text" name="qzmc" class="form-input" value="${isEdit ? data.qzmc : ''}" required>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">权重值</label>
                        <input type="number" name="qz" class="form-input" value="${isEdit ? data.qz : 0}" step="0.01" min="0" max="1" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">测评类型</label>
                        <select name="cplx" class="form-input" required>
                            <option value="">请选择</option>
                            <option value="0" ${isEdit && data.cplx === '0' ? 'selected' : ''}>对教师</option>
                            <option value="1" ${isEdit && data.cplx === '1' ? 'selected' : ''}>对部门</option>
                        </select>
                    </div>
                </div>
                <div style="text-align: right; margin-top: 20px;">
                    <button type="button" class="btn btn-secondary" onclick="CommonModule.closeModal()">取消</button>
                    <button type="button" class="btn btn-primary" onclick="EvaluationContentModule.saveIndicatorWeight(${isEdit})">${isEdit ? '更新' : '保存'}</button>
                </div>
            </form>
        `;
        
        CommonModule.showModal(title, content);
        window.currentEditData = data;
    },

    saveIndicatorWeight(isEdit) {
        const form = document.getElementById('indicatorWeightForm');
        const formData = new FormData(form);
        
        // 验证必填字段
        const qzmc = formData.get('qzmc');
        const qz = formData.get('qz');
        const cplx = formData.get('cplx');
        
        if (!qzmc || !qzmc.trim()) {
            alert('请输入权重名称');
            return;
        }
        
        if (!qz || parseFloat(qz) < 0 || parseFloat(qz) > 1) {
            alert('请输入有效的权重值（0-1之间）');
            return;
        }
        
        if (!cplx) {
            alert('请选择测评类型');
            return;
        }
        
        const weightData = {
            qzbh: formData.get('qzbh') || null,
            qzmc: qzmc.trim(),
            qz: parseFloat(qz),
            cplx: cplx
        };

        const url = isEdit ?
            `/indicator-weights/${window.currentEditData.qzbh}` :
            '/indicator-weights';
        const method = isEdit ? 'PUT' : 'POST';

        CommonModule.apiRequest(url, {
            method: method,
            body: JSON.stringify(weightData)
        })
        .then(response => response.json())
        .then(result => {
            if (result.code === 200) {
                CommonModule.showSuccess(isEdit ? '更新成功' : '添加成功');
                CommonModule.closeModal();
                this.loadIndicatorWeightsList();
            } else {
                alert(`${isEdit ? '更新' : '添加'}失败：${result.message}`);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '保存权重');
        });
    },

    editIndicatorWeight(qzbh) {
        CommonModule.apiRequest(`/indicator-weights/${qzbh}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    this.showIndicatorWeightModal(data.data);
                } else {
                    alert('获取权重信息失败：' + data.message);
                }
            })
            .catch(error => {
                CommonModule.handleApiError(error, '获取权重详情');
            });
    },

    deleteIndicatorWeight(qzbh) {
        if (!CommonModule.confirmAction('确认删除该指标权重？删除后不可恢复。')) {
            return;
        }

        CommonModule.apiRequest(`/indicator-weights/${qzbh}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                CommonModule.showSuccess('删除成功');
                this.loadIndicatorWeightsList();
            } else {
                alert('删除失败：' + data.message);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '删除权重');
        });
    },

    searchIndicatorWeights() {
        console.log('searchIndicatorWeights called');
        this.loadIndicatorWeightsList(1);
    },

    importIndicatorWeights() {
        console.log('导入指标权重');
    },

    exportIndicatorWeights() {
        window.location.href = CommonModule.globalConfig.apiBase + '/export/indicator-weights';
    },

    // ========== 测评类型管理 ==========
    loadEvaluationTypeList() {
        CommonModule.apiRequest('/evaluation-types')
            .then(response => response.json())
            .then(data => {
                if (data.code === 200 && data.data) {
                    this.renderEvaluationTypeTable(data.data.list || []);
                } else {
                    CommonModule.handleApiError(new Error(data.message || '加载失败'), '加载测评类型');
                }
            })
            .catch(error => {
                CommonModule.handleApiError(error, '加载测评类型');
            });
    },

    renderEvaluationTypeTable(types) {
        const tbody = document.querySelector('#evaluationTypeTableContent table tbody');
        if (!tbody) return;

        tbody.innerHTML = '';
        if (types && types.length > 0) {
            types.forEach(type => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${type.lxbh || ''}</td>
                    <td>${type.lxmc || ''}</td>
                    <td>
                        <button class="btn btn-primary btn-small" onclick="EvaluationContentModule.editEvaluationType('${type.lxbh}')">编辑</button>
                        <button class="btn btn-danger btn-small" onclick="EvaluationContentModule.deleteEvaluationType('${type.lxbh}')">删除</button>
                    </td>
                `;
                tbody.appendChild(row);
            });
        } else {
            tbody.innerHTML = '<tr><td colspan="3">暂无数据</td></tr>';
        }
    },

    showEvaluationTypeModal(data = null) {
        const isEdit = data !== null;
        const title = isEdit ? '编辑测评类型' : '新增测评类型';
        
        const content = `
            <form id="evaluationTypeForm">
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">类型编号</label>
                        <input type="text" name="lxbh" class="form-input" value="${isEdit ? data.lxbh : ''}" 
                               ${isEdit ? 'readonly' : ''} placeholder="${isEdit ? '' : '系统自动生成'}">
                    </div>
                    <div class="form-group">
                        <label class="form-label">类型名称</label>
                        <input type="text" name="lxmc" class="form-input" value="${isEdit ? data.lxmc : ''}" required>
                    </div>
                </div>
                <div style="text-align: right; margin-top: 20px;">
                    <button type="button" class="btn btn-secondary" onclick="CommonModule.closeModal()">取消</button>
                    <button type="button" class="btn btn-primary" onclick="EvaluationContentModule.saveEvaluationType(${isEdit})">${isEdit ? '更新' : '保存'}</button>
                </div>
            </form>
        `;
        
        CommonModule.showModal(title, content);
        window.currentEditData = data;
    },

    saveEvaluationType(isEdit) {
        const form = document.getElementById('evaluationTypeForm');
        const formData = new FormData(form);
        
        const typeData = {
            lxbh: formData.get('lxbh') || null,
            lxmc: formData.get('lxmc')
        };

        const url = isEdit ?
            `/evaluation-types/${window.currentEditData.lxbh}` :
            '/evaluation-types';
        const method = isEdit ? 'PUT' : 'POST';

        CommonModule.apiRequest(url, {
            method: method,
            body: JSON.stringify(typeData)
        })
        .then(response => response.json())
        .then(result => {
            if (result.code === 200) {
                CommonModule.showSuccess(isEdit ? '更新成功' : '添加成功');
                CommonModule.closeModal();
                this.loadEvaluationTypeList();
            } else {
                alert(`${isEdit ? '更新' : '添加'}失败：${result.message}`);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '保存测评类型');
        });
    },

    editEvaluationType(lxbh) {
        CommonModule.apiRequest(`/evaluation-types/${lxbh}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    this.showEvaluationTypeModal(data.data);
                } else {
                    alert('获取测评类型信息失败：' + data.message);
                }
            })
            .catch(error => {
                CommonModule.handleApiError(error, '获取测评类型详情');
            });
    },

    deleteEvaluationType(lxbh) {
        if (!CommonModule.confirmAction('确认删除该测评类型？删除后不可恢复。')) {
            return;
        }

        CommonModule.apiRequest(`/evaluation-types/${lxbh}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                CommonModule.showSuccess('删除成功');
                this.loadEvaluationTypeList();
            } else {
                alert('删除失败：' + data.message);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '删除测评类型');
        });
    },

    importEvaluationTypes() {
        console.log('导入测评类型');
    },

    exportEvaluationTypes() {
        window.location.href = CommonModule.globalConfig.apiBase + '/export/evaluation-types';
    }
};

// 全局函数用于Tab切换
function switchEvaluationTab(tabName) {
    EvaluationContentModule.switchTab(tabName);
}

// 导出模块
window.EvaluationContentModule = EvaluationContentModule; 